package com.shenzhen.horselive.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flqy.baselibrary.utils.L;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.MapLimitAddrAdapter;
import com.shenzhen.horselive.adapter.MapLimitTabAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.BaseActivity;
import com.shenzhen.horselive.beans.CodeBean;
import com.shenzhen.horselive.beans.FabuFanwei;
import com.shenzhen.horselive.beans.LimitRange;
import com.shenzhen.horselive.databinding.ActivityRedPackageLimitBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.utils.GetJsonDataUtil;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.httpresponse.Poi;
import com.tencent.lbssearch.object.param.Geo2AddressParam;
import com.tencent.lbssearch.object.param.SearchParam;
import com.tencent.lbssearch.object.result.Geo2AddressResultObject;
import com.tencent.lbssearch.object.result.SearchResultObject;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.maps.model.TencentMapGestureListener;

import java.util.ArrayList;
import java.util.List;

public class RedPackageLimitActivity extends BaseActivity {

    ActivityRedPackageLimitBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRedPackageLimitBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //状态栏
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .init();
        initViews();
        initData();
        //定位
        location();
    }

    TencentMap  tencentMap;
    TencentLocationManager locationManager;
    private  void  location()
    {
        if (locationManager==null)
            locationManager = TencentLocationManager.getInstance(this);
        //单点定位
        String[] permissions = {
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION,
                Permission.READ_PHONE_STATE,
                Permission.WRITE_EXTERNAL_STORAGE,
        };

        XXPermissions.with(this)
                .permission(permissions
                )
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all)
                        {

                            TencentLocationRequest request = TencentLocationRequest.create();
                            request.setRequestLevel(3).setInterval(5000)
                            ;
                            int error = locationManager.requestLocationUpdates(request, locationListener, Looper.getMainLooper());
                            if (error == 0)
                                Log.e("addr","注册位置监听器成功！");
                            else
                                Log.e("addr","注册位置监听器失败！");
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });


    }

    private  String  city;
    private  String  provence;
    private  String  direct;
    private TencentLocationListener locationListener = new TencentLocationListener() {
        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {

            if(i == TencentLocation.ERROR_OK){
                city = tencentLocation.getCity();
                provence =  tencentLocation.getProvince();
                direct = tencentLocation.getDistrict();
                locationManager.removeUpdates(locationListener);
                LatLng position = new LatLng(tencentLocation.getLatitude(),tencentLocation.getLongitude());
                //定位标记点
//                tencentMap.addMarker(new MarkerOptions(position)
//                );
                tencentMap.moveCamera(CameraUpdateFactory
                        .newLatLngZoom(position,14.2f));
                //执行一次搜索
                reGeocoder(new LatLng(tencentLocation.getLatitude(),tencentLocation.getLongitude()));
            }
            else
            {
                Log.v("map",i+s);
            }

        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    };

    private void initData() {
        ApiFactory.getApiService().getLimitRange(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<LimitRange>(this) {
                    @Override
                    protected void onNextInActive(LimitRange limitRange) {
                        if (limitRange.isSuccess())
                        {
                            //选中第几个
                            for (int i = 0; i < limitRange.getData().size(); i++) {
                                if (limitRange.getData().get(i).getIsUsed()==1)
                                {
                                    tabAdapter.setPosition(i);
                                    break;
                                }
                            }
                            tabAdapter.setNewData(limitRange.getData());
                        }else
                        {
                           showToast(limitRange.getErrMessage());
                        }
                    }
                });
    }

    MapLimitTabAdapter  tabAdapter;
    MapLimitAddrAdapter  addrAdapter;
    private void initViews() {
        tencentMap =  binding.mapView.getMap();
        LinearLayoutManager  manager = new LinearLayoutManager(RedPackageLimitActivity.this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.recyclerviewMiles.setLayoutManager(manager);
         tabAdapter =  new MapLimitTabAdapter(R.layout.item_limit_tab);
        binding.recyclerviewMiles.setAdapter(tabAdapter);
        tabAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (tabAdapter.getData().get(position).getIsUsed()==1)
                {
                tabAdapter.setPosition(position);
                }
                else
                {
                    showToast("当前范围不可用");
                }
            }
        });
         addrAdapter =  new MapLimitAddrAdapter(R.layout.item_limit_addr);
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerview.setAdapter(addrAdapter);
       addrAdapter.setOnItemClickListener(new OnItemClickListener() {
           @Override
           public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
               addrAdapter.setPosition(position);
           }
       });

        binding.imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        binding.etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //执行搜索的代码
                    searchAddrs();
                }
                return false;
            }
        });


        //确定选择
        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               submit();
            }
        });


        //地图拖拽监听
       tencentMap.addTencentMapGestureListener(new TencentMapGestureListener() {
           @Override
           public boolean onDoubleTap(float v, float v1) {
               return false;
           }

           @Override
           public boolean onSingleTap(float v, float v1) {
               return false;
           }

           @Override
           public boolean onFling(float v, float v1) {
               return false;
           }

           @Override
           public boolean onScroll(float v, float v1) {
               return false;
           }

           @Override
           public boolean onLongPress(float v, float v1) {
               return false;
           }

           @Override
           public boolean onDown(float v, float v1) {

               return false;
           }

           @Override
           public boolean onUp(float v, float v1) {
               //手指抬起的时候
//               tencentMap.getCameraPosition().target
               Log.e("addr",tencentMap.getCameraPosition().target.latitude+"");
               Log.e("addr",tencentMap.getCameraPosition().target.longitude+"");
               LatLng  latLng =  new LatLng(tencentMap.getCameraPosition().target.latitude
               ,tencentMap.getCameraPosition().target.longitude
               );
               reGeocoder(latLng);
               return false;
           }

           @Override
           public void onMapStable() {

           }
       });




    }

    //确认返回
    private void submit() {
        if (tabAdapter.getItemCount()==0||addrAdapter.getItemCount()==0)
        {
            return;
        }

     int  range =    tabAdapter.getData().get(tabAdapter.getSelection()).getRangeValue();
        String  name =tabAdapter.getData().get(tabAdapter.getSelection()).getRangeDesc();
        String  addrname =  addrAdapter.getData().get(addrAdapter.getSelection()).address;
        double  lat =  addrAdapter.getData().get(addrAdapter.getSelection()).latLng.latitude;
        double  lng =  addrAdapter.getData().get(addrAdapter.getSelection()).latLng.longitude;
        FabuFanwei  fabuFanwei = new FabuFanwei();
        fabuFanwei.setAddrname(addrname);
        fabuFanwei.setRange(range);
        fabuFanwei.setLat(lat);
        fabuFanwei.setLng(lng);
        fabuFanwei.setName(name);

        //
        fabuFanwei.setProvence(provence);
        fabuFanwei.setCity(city);
        fabuFanwei.setDirect(direct);

        CodeBean  codeBean = GetJsonDataUtil.getInstance().getCode(provence,city,direct);
        fabuFanwei.setProvenceCode(codeBean.getProvinceCode());
        fabuFanwei.setCityCode(codeBean.getCityCode());
        fabuFanwei.setDirectCode(codeBean.getDistrictCode());


        Intent  intent = new Intent();
        intent.putExtra("data",fabuFanwei);
        setResult(1001,intent);
        finish();
    }

    private void searchAddrs() {
        String  string =binding.etSearch.getText().toString();
        if (TextUtils.isEmpty(string))
        {
            return;
        }
        TencentSearch tencentSearch = new TencentSearch(this);
        String keyWord = string.trim();
        //城市搜索
        SearchParam.Region region = new SearchParam
                //设置搜索城市
                .Region(city)
                .autoExtend(true)
                //设置搜索范围不扩大
               ;
        //构建地点检索
        SearchParam searchParam = new SearchParam(keyWord,region);
        tencentSearch.search(searchParam, new HttpResponseListener<BaseObject>() {

            @Override
            public void onFailure(int arg0, String arg2,
                                  Throwable arg3) {
                Toast.makeText(getApplicationContext(), arg2, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(int arg0, BaseObject arg1) {
                if (arg1 == null) {
                    return;
                }
                SearchResultObject obj = (SearchResultObject) arg1;
                if(obj.data == null||obj.data.size()==0){
                    return;
                }
                //将地图中心坐标移动到检索到的第一个地点
                tencentMap.moveCamera(CameraUpdateFactory
                        .newCameraPosition(
                                new CameraPosition(obj.data.get(0).latLng,
                                        //设置缩放级别到 15 级
                                        15f,
                                        0,
                                        0)));
                //将其他检索到的地点在地图上用 marker 标出来
//                for(SearchResultObject.SearchResultData data : obj.data){
//                    tencentMap.addMarker(new MarkerOptions()
//                            //标注的位置
//                            .position(data.latLng)
//                            //标注的InfoWindow的标题
//                            .title(data.title)
//                            //标注的InfoWindow的内容
//                            .snippet(data.address)
//                    );
//                }
              addrAdapter.setNewData(obj.data);
            }
        });


    }


    @Override
    protected void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        binding.mapView.onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        binding.mapView.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }




    /**
     * 逆地理编码
     */
    protected void reGeocoder(LatLng  latLng) {

        if (latLng == null) {
            return;
        }
        TencentSearch tencentSearch = new TencentSearch(this);
        //还可以传入其他坐标系的坐标，不过需要用coord_type()指明所用类型
        //这里设置返回周边poi列表，可以在一定程度上满足用户获取指定坐标周边poi的需求
        Geo2AddressParam geo2AddressParam = new Geo2AddressParam(latLng).getPoi(true)
                .setPoiOptions(new Geo2AddressParam.PoiOptions()
                        .setRadius(1000)
                        );
        tencentSearch.geo2address(geo2AddressParam, new HttpResponseListener<BaseObject>() {

            @Override
            public void onSuccess(int arg0, BaseObject arg1) {
                if (arg1 == null) {
                    return;
                }
                Geo2AddressResultObject obj = (Geo2AddressResultObject)arg1;
                StringBuilder sb = new StringBuilder();
                sb.append("逆地址解析");
                sb.append("\n地址：" + obj.result.address);
                sb.append("\npois:");

                List< SearchResultObject.SearchResultData>  list =  new ArrayList<>();
                SearchResultObject.SearchResultData data ;
                for (Poi poi : obj.result.pois) {
                    data = new SearchResultObject.SearchResultData();
                    data.title =poi.title;
                    data.address = poi.address;
                    data.latLng  =poi.latLng;
                    list.add(data);
//                    tencentMap.addMarker(new MarkerOptions()
//                            .position(poi.latLng)  //标注的位置
//                            .title(poi.title)     //标注的InfoWindow的标题
//                            .snippet(poi.address) //标注的InfoWindow的内容
//                    );
                }
                addrAdapter.setNewData(list);
                Log.e("test", sb.toString());
            }

            @Override
            public void onFailure(int arg0, String arg1, Throwable arg2) {
                Log.e("test", "error code:" + arg0 + ", msg:" + arg1);
            }
        });
    }



}